package controller.webservice.bootstrap;

import java.io.IOException;

import manager.BidMgr;
import manager.StudentMgr;
import controller.RoundCtrl;
import controller.validator.BidValidator;
import entity.Bid;
import entity.Round;
import exception.InputValidationErrors;

/**
 * Validates and loads bid CSV.
 * 
 * @author huangjm.2012, jaslin.wee.2012, sheryl.tay.2012
 * 
 */
public class BidsCsvLoader extends CsvLoader {

	private BidMgr bidMgr;
	private StudentMgr studentMgr;
	private RoundCtrl roundCtrl;

	BidsCsvLoader(String pathToFile) throws IOException {
		super(pathToFile);
		bidMgr = new BidMgr();
		studentMgr = new manager.StudentMgr();
		roundCtrl = new RoundCtrl();
	}

	@Override
	boolean loadRow() throws InputValidationErrors {

		String userId = getValue("userid");
		String bidAmountStr = getValue("amount");
		String courseCode = getValue("code");
		String sectionCode = getValue("section");

		BidValidator validator = new BidValidator(userId, courseCode,
				sectionCode, bidAmountStr);
		validator.performValidationBeforeAdding();

		if (validator.hasPreviousBid()) {
			bidMgr.deleteBid(userId, courseCode);
		}

		Bid bid = validator.getBid();
		boolean isBidAdded = bidMgr.addBid(bid);
		if (isBidAdded) {
			studentMgr.updateEdollarForStudent(
					validator.getUpdatedEdollarForStudent(), userId);
		}

		if (roundCtrl.isCurrentRoundNo(Round.ROUND_TWO)) {
			roundCtrl.computeAndStoreMinBidAmountForSectionInRoundTwo(bid
					.getSection());
		}

		return isBidAdded;

	}

}
